package com.hema.auction.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.base.BaseRechargeActivity;
import com.hema.auction.bean.BackConfig;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.UrlManager;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.GlideUtils;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.MyClickable;
import com.hema.auction.widget.view.TitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.hema.auction.http.HttpTag.TAG_DO_BACK_AUCTION;

/**
 * 描述:不中包赔
 * 作者:john
 */
public class CompensationActivity extends BaseRechargeActivity {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.iv_good_icon)
    ImageView ivGoodIcon;
    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_pay_price)
    TextView tvPayPrice;
    @BindView(R.id.cb_agreement)
    CheckBox cbAgreement;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.tv_back1)
    TextView tvBack1;
    @BindView(R.id.tv_continuity1)
    TextView tvContinuity1;
    @BindView(R.id.tv_back2)
    TextView tvBack2;
    @BindView(R.id.tv_continuity2)
    TextView tvContinuity2;
    @BindView(R.id.tv_back3)
    TextView tvBack3;
    @BindView(R.id.tv_continuity3)
    TextView tvContinuity3;
    @BindView(R.id.rb_alipay)
    RadioButton rbAlipay;
    @BindView(R.id.rb_wechat)
    RadioButton rbWechat;

    private String goodId;
    private List<BackConfig> configs = new ArrayList<>();
    private BackConfig indexConfig;
    private String configId, transId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compensation);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        showProgressDialog();
        HttpManager.getInstance(this).getBackSale(this);
        tvAgreement.setText(getClickableSpan());
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());

        rbAlipay.setOnClickListener(view -> {
            rbAlipay.setChecked(true);
            rbWechat.setChecked(false);
            payType = "alipay_h5";
        });
        rbWechat.setOnClickListener(view -> {
            payType = "wechat_h5";
            rbWechat.setChecked(true);
            rbAlipay.setChecked(false);
        });

    }

    private CharSequence getClickableSpan() {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString(Constant.EXTRA_TITLE, getString(R.string.reg_agreement));
                bundle.putString(Constant.EXTRA_URL, UrlManager.H5_AGREEMENT);
                intentTo(H5Activity.class, bundle);
            }
        };
        SpannableString spanableInfo = new SpannableString(tvAgreement.getText().toString());
        int start = 4;
        int end = 10;
        spanableInfo.setSpan(new MyClickable(this, listener), start, end, Spanned.SPAN_MARK_MARK);
        return spanableInfo;
    }


    @OnClick({R.id.tv_continuity1, R.id.tv_continuity2, R.id.tv_continuity3, R.id.tv_pay, R.id.tv_rule})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_continuity1:
                tvContinuity1.setSelected(true);
                tvContinuity2.setSelected(false);
                tvContinuity3.setSelected(false);
                setPayPrice(0);
                break;
            case R.id.tv_continuity2:
                tvContinuity2.setSelected(true);
                tvContinuity1.setSelected(false);
                tvContinuity3.setSelected(false);
                setPayPrice(1);
                break;
            case R.id.tv_continuity3:
                tvContinuity3.setSelected(true);
                tvContinuity1.setSelected(false);
                tvContinuity2.setSelected(false);
                setPayPrice(2);
                break;
            case R.id.tv_pay:
                if (isLogin) {
                    if (cbAgreement.isChecked()) {
//                        isAutoDismissDialog = false;
//                        showProgressDialog();
                        HttpManager.getInstance(this).compensationPay(String.valueOf(indexConfig.getSumCost()), goodId, configId, payType, this);
//                        HttpManager.getInstance(this).compensationPay("2", goodId, configId, this);
                    } else {
                        showToastSafe(R.string.please_agree_privacy_agreement);
                    }
                } else {
                    goLogin();
                }
                break;
            case R.id.tv_rule:
                /**
                 * 详情规则
                 */
                Bundle bundle = new Bundle();
                bundle.putString(Constant.EXTRA_TITLE, getString(R.string.detail_rule));
                bundle.putString(Constant.EXTRA_URL, UrlManager.H5_RULE_BZ);
                intentTo(H5Activity.class, bundle);
                break;
        }
    }

    /**
     * 更新付付款价格
     *
     * @param position
     */
    private void setPayPrice(int position) {
        if (configs != null) {
            indexConfig = configs.get(position);
            tvPayPrice.setText(Utils.priceUnitFormat(this, String.valueOf(indexConfig.getSumCost())));
            tvTip.setText(getString(R.string.compensation_tips, indexConfig.getAucNumber(), indexConfig.getRetNumber()));
            configId = indexConfig.getId();
        }
    }

    /**
     * 设置连拍次数和反币数据
     */
    private void configData() {
        if (configs != null) {
            for (int i = 0; i < configs.size(); i++) {
                BackConfig config = configs.get(i);
                switch (i) {
                    case 0:
                        tvBack1.setText(getString(R.string.back_format, config.getRetNumber()));
                        tvContinuity1.setText(getString(R.string.continuity_format, config.getAucNumber()));
                        tvContinuity1.setSelected(true);
                        tvContinuity2.setSelected(false);
                        tvContinuity3.setSelected(false);
                        setPayPrice(0);
                        break;
                    case 1:
                        tvBack2.setText(getString(R.string.back_format, config.getRetNumber()));
                        tvContinuity2.setText(getString(R.string.continuity_format, config.getAucNumber()));
                        break;
                    case 2:
                        tvBack3.setText(getString(R.string.back_format, config.getRetNumber()));
                        tvContinuity3.setText(getString(R.string.continuity_format, config.getAucNumber()));
                        break;
                }
            }
        }
    }

    @Override
    protected void paySuccess() {
        super.paySuccess();
        isAutoDismissDialog = false;
        showProgressDialog();
        HttpManager.getInstance(this).doBackAuction(goodId, indexConfig.getId(), this);
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_BACK_SALE:
                try {
                    if (result.getInt("errcode") == 0) {
                        JSONObject data = result.getJSONObject("data");
                        goodId = data.getString("good_id");
                        GlideUtils.load(this, data.getString("good_pic"), ivGoodIcon);
                        tvGoodName.setText(data.getString("good_name"));
                        tvPrice.setText(Utils.priceUnitFormat(this, data.getString("now_price")));
                        configs = new Gson().fromJson(data.getJSONArray("back_config").toString(), new TypeToken<List<BackConfig>>() {
                        }.getType());
                        configData();
                    } else {
                        showToastSafe(result);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DO_BACK_AUCTION:
                try {
                    if (result.getInt("errcode") == 0) {
                        if (!result.isNull("data"))
                            goodId = result.getString("data");
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.EXTRA_GOOD_ID, goodId);
                        intentTo(GoodsDetailsActivity.class, bundle);
                        finish();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_DO_ORDER:
                try {
                    if (result.getInt("errcode") == 0) {
                        JSONObject data = result.getJSONObject("data");
                        transId = data.getString("transid");
                        startPay(3, transId, indexConfig.getSumCost());
//                        orderSn = data.getString("orderSn");
//                        String payUrl = data.getString("payUrl");
//                        toPay(3, payUrl);
                    } else {
                        showToastSafe(result);
                        dismissProgressDialog();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
                break;
        }
    }


    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        if (httpTag == TAG_DO_BACK_AUCTION) {
            dismissProgressDialog();
        }
    }

}
